package com.meilai.project.service.finance.payment.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meilai.project.dto.finance.payment.PaymentWriteOffApplyCheckDTO;
import com.meilai.project.dto.finance.payment.PaymentWriteOffApplyDTO;
import com.meilai.project.dto.workflow.FlowBusinessDataSuperEntity;
import com.meilai.project.dto.workflow.WorkFlowCheckDTO;
import com.meilai.project.entity.finance.payment.PaymentWriteOffApply;
import com.meilai.project.exception.CommonException;
import com.meilai.project.mapper.payment.PaymentApplyMapper;
import com.meilai.project.mapper.payment.PaymentWriteOffApplyMapper;
import com.meilai.project.service.finance.payment.PaymentWriteOffApplyService;
import com.meilai.project.service.system.impl.UserServiceImpl;
import com.meilai.project.util.ThreadLocalUserUtil;
import com.meilai.project.util.WorkFlowUtil;
import com.meilai.project.vo.finance.payment.PaymentApplyVO;
import com.meilai.project.vo.system.UserForWFVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 付款单 服务实现类
 * </p>
 *
 * @author xchen
 * @since 2022-02-12
 */
@Service
public class PaymentWriteOffApplyServiceImpl extends ServiceImpl<PaymentWriteOffApplyMapper, PaymentWriteOffApply> implements PaymentWriteOffApplyService {

    @Autowired
    private PaymentApplyMapper paymentApplyMapper;

    @Override
    public PaymentApplyVO getOneById(Long id) {
        PaymentApplyVO result = baseMapper.getOneById(id);
        if (result == null) throw new CommonException("数据不存在！");
        if (null != id) {
            Long userId = ThreadLocalUserUtil.get().getId();
            Boolean canCheck = WorkFlowUtil.canCheckData(userId, result);
            result.setCan_check(canCheck);
            result.setIs_applyer(userId.equals(result.getFlow_applyer_id()));
        } else {
            result.setIs_applyer(true);
        }
        return result;
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean save(PaymentWriteOffApplyDTO dto) {
        int flowResult = saveAndBegin(dto, true);
        if (flowResult != 1) throw new CommonException("保存至草稿箱失败，请联系管理员！");
        else return true;
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean begin(PaymentWriteOffApplyDTO dto) {
        // 提交
        int flowResult = saveAndBegin(dto, false);
        if (flowResult == 1) {
            // 仍在流程中
            return true;
        } else if (flowResult == 2) {
            // 无审批节点，直接结束
            endProcess(dto.getId());
            return true;
        } else {
            throw new CommonException("提交失败，请联系管理员！");
        }
    }

    private void endProcess(Long id) {
        //end process
        PaymentWriteOffApply apply = getById(id);
        if(null != apply) {
            paymentApplyMapper.markWriteOff(apply.getPayment_id());
        }
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean pass(PaymentWriteOffApplyCheckDTO dto) {
        // 通过
        int flowResult = passAndBack(dto, true, false);
        if (flowResult == 1) {
            // 通过后仍然在流程中
            return true;
        } else if (flowResult == 2) {
            // 审核后流程结束
            // 更新roster表
            endProcess(dto.getId());
            return true;
        } else {
            throw new CommonException("通过失败，请联系管理员！");
        }
    }

    private int saveAndBegin(PaymentWriteOffApplyDTO dto, boolean isSave) {
        // 获取当前人的id和部门id
        UserForWFVO user = UserServiceImpl.getUserForWF(dto);
        PaymentWriteOffApply temp = new PaymentWriteOffApply();
        BeanUtils.copyProperties(dto, temp);

        // 设置流程字段，flow_type请自行对应“dict_flow_type”表中的id， 比如当前入职流程（考察登记流程）的id是5
        String flow_title = "付款核销申请"; // 审批流程的名称，需要根据实际业务自行确定
        FlowBusinessDataSuperEntity fbdse = WorkFlowUtil.getStartSuperDataEntity(
                user.getUser_id(),  // 当前用户id
                user.getDep_id(), // 提交的部门id
                16, // 流程类型id，“dict_flow_type”表中的id
                flow_title // 自定义的流程标题
        );
        BeanUtils.copyProperties(fbdse, temp);

        // 是否为新数据
        // 新数据时，前端不传业务数据id
        // 非新数据时，即来源是“草稿箱”、“已删除”、“被退回”时，前端需要传入业务数据id
        boolean isFirst = (dto.getId() == null);

        // 由于流程字段含有id，会覆盖数据，此处需要手动setId
        if (!isFirst) temp.setId(dto.getId());

        boolean flag = isFirst ? save(temp) : updateById(temp);
        if (!flag) throw new CommonException("保存失败");

        // 构造流程工具类
        WorkFlowUtil wfu = new WorkFlowUtil<PaymentWriteOffApply, PaymentWriteOffApplyMapper>(temp.getId(), user.getUser_id(), PaymentWriteOffApply.class);

        // 审批流程id
        // 新数据,传0L
        // 非新数据,根据数据id,查找wfData_id
        Long wfData_id = isFirst ? 0L : wfu.getWfDataId(dto.getId());
        // 旧数据记录留存
        PaymentWriteOffApply old_data = isFirst ? new PaymentWriteOffApply() : temp;

        return isSave ? wfu.SaveDraft(wfData_id) : wfu.Begin(wfData_id, "", old_data);
    }

    private int passAndBack(PaymentWriteOffApplyCheckDTO dto, boolean isPass, boolean... updateData) {
        // 当前人id
        Long userId = ThreadLocalUserUtil.get().getId();

        // 若业务数据有审批中可修改的内容，请自行更新
        if (updateData != null && updateData[0]) {
            PaymentWriteOffApply updateTemp = new PaymentWriteOffApply();
            BeanUtils.copyProperties(dto, updateTemp);
            updateById(updateTemp);
        }

        // 业务数据
        PaymentWriteOffApply temp = getById(dto.getId());

        // 构造流程工具类
        WorkFlowUtil wfu = new WorkFlowUtil<PaymentWriteOffApply, PaymentWriteOffApplyMapper>(dto.getId(), userId, PaymentWriteOffApply.class);

        // 审批入参类
        WorkFlowCheckDTO checkDTO = WorkFlowCheckDTO.getWorkFlowCheckDTO(
                temp.getFlow_current_node_id(), // 当前节点id
                temp.getFlow_json(), // 流程json
                dto.getWf_check_opinion(), // 审批意见
                dto.getWf_check_sign_url(), // 审批签名链接
                JSONObject.toJSONString(temp) // 旧数据留存
        );

        // 审批
        return isPass ? wfu.ToNext(checkDTO) : wfu.ReturnBack(checkDTO);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean returnBack(PaymentWriteOffApplyCheckDTO dto) {
        // 驳回
        int flowResult = passAndBack(dto, false, false);
        if (flowResult != 1) throw new CommonException("驳回失败，请联系管理员！");
        return true;
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean delete(Long id) {
        int flowResult = deleteAndActualDel(id, false);
        if (flowResult != 1) throw new CommonException("删除失败，请联系管理员！");
        return true;
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean actualDelete(Long id) {
        int flowResult = deleteAndActualDel(id, true);
        if (flowResult != 1) throw new CommonException("彻底删除失败，请联系管理员！");
        return true;
    }

    // 删除 和 彻底删除 抽出相同代码
    private int deleteAndActualDel(Long id, boolean isActual) {
        // 当前人id
        Long userId = ThreadLocalUserUtil.get().getId();

        //回滚报销状态
        PaymentWriteOffApply apply = getById(id);
        if(null != apply) {
            paymentApplyMapper.markWriteOffBack(apply.getPayment_id());
        }

        // 构造流程工具类
        WorkFlowUtil wfu = new WorkFlowUtil<PaymentWriteOffApply, PaymentWriteOffApplyMapper>(id, userId, PaymentWriteOffApply.class);

        // 流程id
        Long wfData_id = wfu.getWfDataId(id);

        return isActual ? wfu.ActualDelete(wfData_id) : wfu.Delete(wfData_id);
    }
}
